package com.gitee.ice1938.module.admin.sysoption.fun;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * 数据库配置--不提供插入方法，数据插入需各模块使用sql进行初始化。
 * 
 * @author ice1938@qq.com
 *
 */
@Repository
class OptionsRepository implements Serializable {

	private static final String sys_option = "cache_sys_option";

	/**
	 * 
	 */
	private static final long serialVersionUID = 70313854653319954L;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 根据optionName 获得optionValue
	 *
	 * @param optionName
	 * @return
	 */
	@Cacheable(value = sys_option, key = "'getOption_'+ #p0")
	public String getOption(String optionName) {
		String optionValue;
		try {
			String sql = "SELECT option_value FROM sys_option where option_name = ? ";
			optionValue = jdbcTemplate.queryForObject(sql, String.class, optionName);
		} catch (EmptyResultDataAccessException e) {
			optionValue = null;
		}
		return optionValue;
	}

	@Cacheable(value = sys_option)
	public List<Map<String, Object>> queryOptions(String... optionName) {
		List<Map<String, Object>> data;
		try {
			StringBuilder sql = new StringBuilder("SELECT * FROM sys_option");
			if (optionName.length > 0) {
				sql.append(" where option_name in (");
				for (int i = 0; i < optionName.length; i++) {
					if (i == 0) {
						sql.append("?");
					} else {
						sql.append(",?");
					}
				}
				sql.append(")");
				data = jdbcTemplate.queryForList(sql.toString(), optionName);
			} else {
				data = jdbcTemplate.queryForList(sql.toString());
			}
		} catch (EmptyResultDataAccessException e) {
			data = null;
		}
		return data;
	}

	@CacheEvict(value = sys_option, allEntries = true)
	public int saveOption(String optionName, String optionValue) {
		String sql = "UPDATE sys_option  SET option_value = ?  WHERE option_name =? ";
		int update = jdbcTemplate.update(sql, new Object[] { optionValue, optionName });
		return update;

	}

	@CacheEvict(value = sys_option, allEntries = true)
	public int insertOption(String optionName, String optionValue, String optionTilte, String optionDesc) {
		String sql = "insert INTO sys_option (option_value,option_name,option_tilte,option_desc) VALUES (?,?,?,?)";
		int update = jdbcTemplate.update(sql.toString(),
		        new Object[] { optionValue, optionName, optionTilte, optionDesc });
		return update;

	}
}
